﻿using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using Vra.DataAccess.Attributes;

namespace Vra.DataAccess
{
	public class BaseDao
	{
		private const string ConnectinoStringName = "vradb";

		/// <summary>
		/// Возвращает объект подключения к базе
		/// </summary>
		/// <returns></returns>
		protected static SqlConnection GetConnection()
		{
			return new SqlConnection(GetConnectionString());
		}

		/// <summary>
		/// Возвращает строку подключения к базе
		/// </summary>
		/// <returns></returns>
		private static string GetConnectionString()
		{
			return ConfigurationManager.ConnectionStrings[ConnectinoStringName].ConnectionString;
		}

		protected static string LoadIdentityValue(object data)
		{
			return data == null ? null : GetIdentityValue(data);
		}

		private static string GetIdentityValue(object item)
		{
			var field = item.GetType().GetFields().First(p => p.GetCustomAttributes(typeof(ColumnAttribute), true)
								.Cast<ColumnAttribute>()
								.Any(q => q.IsIdentity));
			object res = field.GetValue(item);
			return res == null ? null : res.ToString();
		}
	}
}